package com.heima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.heima.config.AliOssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.util.UUID;

@Component
public class AliOssUtil {

    @Autowired
    private AliOssProperties aliOssProperties;

    public String upload(byte[] bytes, String originalFilename) {
        // 文件名加 UUID 防止重复
        String fileName = UUID.randomUUID().toString().replace("-", "") + "_" + originalFilename;

        // 创建 OSSClient
        OSS ossClient = new OSSClientBuilder().build(
                aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret()
        );

        try {
            // 上传文件
            ossClient.putObject(aliOssProperties.getBucketName(), fileName, new ByteArrayInputStream(bytes));
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        // 拼接访问 URL
        return "https://" + aliOssProperties.getBucketName() + "."
                + aliOssProperties.getEndpoint() + "/" + fileName;
    }
}
